﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using BlogPlat.Model;
using BlogPlat.Model.Abstract;
using System.Data.Linq;

namespace BlogPlat.Model.Repositories
{
    public class TagRepository : IRepository<Tag>, IFriendlyUrl<Tag>
    {
        private Table<Tag> _tags;
        private Table<TaggedPost> _taggedPosts;

        public TagRepository(string connString)
        {
            _tags = (new DataContext(connString)).GetTable<Tag>();
            _taggedPosts = (new DataContext(connString)).GetTable<TaggedPost>();
        }

        #region Interface IRepository<I> Implementation
        public void Add(Tag newEntity)
        {
            _tags.InsertOnSubmit(newEntity);
        }

        public void Delete(int id)
        {
            Tag entityToDelete = _tags.Where(t => t.TagID == id).SingleOrDefault();
            if (entityToDelete != null)
            {
                if(_tags.Context.GetTable<TaggedPost>().Where(t => t.TagID == entityToDelete.TagID).Count() <= 0)
                    _tags.DeleteOnSubmit(entityToDelete);
            }
        }

        public Tag Get(int id)
        {
            return _tags.Where(t => t.TagID == id).SingleOrDefault();
        }

        public ICollection<Tag> List()
        {
            return _tags.ToList();
        }

        public void Update(Tag entityToUpdate)
        {
            if (entityToUpdate.TagID == 0)
                _tags.InsertOnSubmit(entityToUpdate);
            else if (_tags.GetOriginalEntityState(entityToUpdate) == null)
            {
                _tags.Attach(entityToUpdate);
                _tags.Context.Refresh(RefreshMode.KeepCurrentValues, entityToUpdate);
            }
        }

        public void Save()
        {
            _tags.Context.SubmitChanges();
        }
        #endregion

        public int CountPostsTagged(int tagID)
        {
            return _taggedPosts.Where(t => t.TagID == tagID).Count();
        }

        #region Interface IFriendlyUrl Implementation
        public Tag GetByFriendlyUrl(string friendlyUrl)
        {
            if (!string.IsNullOrEmpty(friendlyUrl))
            {
                return _tags.Where(t => t.FriendlyUrl == friendlyUrl).SingleOrDefault();
            }

            return null;
        }
        #endregion        
    }
}
